package com.wowangz.cms.topic.column.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.topic.column.entity.Column;
import com.wowangz.cms.topic.column.service.ColumnService;
import com.wowangz.cms.topic.column.tree.ColumnTree;

@Controller
@SuppressWarnings("unchecked")
@Scope("prototype")
public class ColumnController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ColumnController.class);

	/**
	 * 删除栏目
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/topic/colunm/deleteColumn.json")
	public void deleteColumn(HttpServletRequest request, HttpServletResponse response) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				Column column = columnService.findOneColumnByMap(map);
				if (column != null) {
					column.setStatusid(SysConstant.RecordStatus.INVALID);
					columnService.updateColumn(column);
					getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
				} else {
					getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
				}
			} else {
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/topic/colunm/getColumnJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getColumnJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			if (StringUtils.isNotEmpty(request.getParameter("parentcolumn"))) {
				map.put("columnid", request.getParameter("parentcolumn"));
			}
			DataResult dataResult = getDataResult(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获得栏目树形列表数据
	 * @param response
	 */
	@RequestMapping(value = "/topic/colunm/getColumnListJson.json", method = RequestMethod.GET)
	public void getColumnListJson(HttpServletResponse response) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		try {
			response.getWriter().write(new Gson().toJson(columnTrees));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private DataResult getDataResult(HttpServletRequest request, PangingParam pangingParam, Map<String, Object> map)
			throws Exception {
		map.put("statusid", SysConstant.RecordStatus.VALID);
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		long resultCount = columnService.findColumnCountByMap(map);
		List<Column> columns = columnService.findColumnByMap(map);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultCount);
		dataStyle.setDataList(queryColumns(columns));
		dataStyle.addDepict("columncode", DataTypeConstant.STRING);// 栏目编号
		dataStyle.addDepict("columnname", DataTypeConstant.STRING);// 栏目名称
		dataStyle.addDepictByFunction("display", SysConstant.Display.class, "getName", new Class[] { long.class });// 是否显示
		dataStyle.addDepict("parentcolumnname", DataTypeConstant.STRING);// 银行名称
		dataStyle.addDepictByFunction("statusid", SysConstant.RecordStatus.class, "getName", new Class[] { long.class });// 状态
		dataStyle.addDepict("id", DataTypeConstant.LONG);
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}

	/**
	 * 查询得到上级部门的名称
	 * 
	 * @param columns
	 * @return
	 */
	private List<Column> queryColumns(List<Column> columns) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		List<Column> list = new ArrayList<Column>();
		for (Column column : columns) {
			if (column.getColumnid() != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", column.getColumnid());
				Column column2 = columnService.findOneColumnByMap(map);
				column.setParentcolumnname(column2.getColumnname());
			}
			list.add(column);
		}
		return list;
	}

	/**
	 * 保存栏目信息
	 * 
	 * @param request
	 * @param column
	 * @param response
	 */
	@RequestMapping(value = "/topic/colunm/saveColumn.json", method = RequestMethod.POST)
	public void saveColumn(HttpServletRequest request, Column column, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
			String columncode = request.getParameter("columncode");
			String parentcolumn = request.getParameter("parentcolumn");
			if (StringUtils.isNotEmpty(parentcolumn)) {
				column.setColumnid(Long.valueOf(parentcolumn));
			}
			column.setInputtime(new Date());
			column.setStatusid(SysConstant.RecordStatus.VALID);
			column.setInputuserid(getUserContext().getLoginUser().getId());
			column.setModifytime(new Date());
			column.setModifyuserid(getUserContext().getLoginUser().getId());
			column.setColumncode(columncode);
			columnService.saveColumn(column);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 进入到添加栏目的页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/colunm/toColumnAdd.web", method = RequestMethod.GET)
	public String toColumnAdd(Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmddSSS");
		model.addAttribute("columncode", "TC" + sdf.format(new Date()));
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		model.addAttribute("columnTrees", columnTrees);
		model.addAttribute("treeJson", new Gson().toJson(columnTrees));
		return "/WEB-INF/jsp/topic/column/columnAdd";
	}

	/**
	 * 进入修改页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/topic/colunm/toColumnEdit.web", method = RequestMethod.GET)
	public String toColumnEdit(Model model, HttpServletRequest request) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmddSSS");
		model.addAttribute("columncode", "TC" + sdf.format(new Date()));
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		model.addAttribute("treeJson", new Gson().toJson(columnTrees));
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			map.put("id", id);
			Column column = columnService.findOneColumnByMap(map);
			model.addAttribute("column", column);
			if (column.getColumnid() != null) {
				map.put("id", column.getColumnid());
				Column column2 = columnService.findOneColumnByMap(map);
				model.addAttribute("parentcolumnname", column2.getColumnname());
				model.addAttribute("parentcolumn", column.getColumnid());
			}
		}
		return "/WEB-INF/jsp/topic/column/columnUpdate";
	}

	@RequestMapping(value = "/topic/colunm/queryColumnList.web", method = { RequestMethod.GET })
	public String queryColumnList(HttpServletRequest request, Model model) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		logger.info(new Gson().toJson(columnTrees));
		model.addAttribute("treeJson", new Gson().toJson(columnTrees));
		return "/WEB-INF/jsp/topic/column/columnList";
	}

	/**
	 * 查看栏目详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/colunm/toColumnView.web", method = RequestMethod.GET)
	public String toColumnView(HttpServletRequest request, Model model) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			map.put("id", id);
			Column column = columnService.findOneColumnByMap(map);
			model.addAttribute("column", column);
			model.addAttribute("display", SysConstant.Display.getName(column.getDisplay()));
			if (column.getColumnid() != null) {
				map.put("id", column.getColumnid());
				Column column2 = columnService.findOneColumnByMap(map);
				model.addAttribute("parentcolumnname", column2.getColumnname());
				model.addAttribute("parentcolumn", column.getColumnid());
			}
		}
		return "/WEB-INF/jsp/topic/column/columnView";
	}

	/**
	 * 修改栏目信息
	 * 
	 * @param request
	 * @param column
	 * @param response
	 */
	@RequestMapping(value = "/topic/colunm/updateColumn.json", method = RequestMethod.POST)
	public void updateColumn(HttpServletRequest request, Column column, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
			String columncode = request.getParameter("columncode");
			String parentcolumn = request.getParameter("parentcolumn");
			if (StringUtils.isNotEmpty(parentcolumn)) {
				column.setColumnid(Long.valueOf(parentcolumn));
			}
			column.setModifytime(new Date());
			column.setModifyuserid(getUserContext().getLoginUser().getId());
			column.setColumncode(columncode);
			columnService.updateColumn(column);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
